
from whiff.middleware import misc
from whiff import resolver
from whiff import whiffenv
from whiff import stream
from whiff.rdjson import jsonParse

example_table_json = """
{
"atts": ["name", "age", "phone"],
"data": [
{"name": "aaron", "age":5, "phone": 1111},
{"name": "betty", "age":15, "phone": 2111},
{"name": "cathy", "age":25, "phone": 3111}
]
}
"""
example_name = "betty"

class table(misc.utility):
    "format table from json representation"
    def __init__(self, namevariable="name", tablevariable="jsonData"):
        self.namevariable = namevariable
        self.tablevariable = tablevariable
    def __call__(self, env, start_response):
        env = resolver.process_cgi(env, parse_cgi=True)
        tvariable = self.param_value(self.tablevariable, env)
        nvariable = self.param_value(self.namevariable, env)
        table_text = resolver.unquote(whiffenv.cgiGet(env, tvariable, example_table_json))
        table_json = self.param_json(table_text, env)
        name = whiffenv.cgiGet(env, nvariable, example_name)
        oldname = whiffenv.cgiGet(env, "oldname", "aaron")
        age = whiffenv.cgiGet(env, "age", "55")
        phone = whiffenv.cgiGet(env, "phone", "8888")
        updateFnName = whiffenv.cgiGet(env, "updateFnName")
        #pr "change row", (oldname, name, age, phone)
        #pr "in json", table_json
        atts = table_json["atts"]
        data = table_json["data"]
        firstrow = nextrow = row = None
        newrow = True
        for r in data:
            rname = r["name"]
            if firstrow is None:
                firstrow = r
            if row is not None and nextrow is None:
                nextrow = r
            if rname==oldname:
                row = r
                newrow = False
        if nextrow is None:
            nextrow = firstrow
        if newrow:
            D = {}
            data.append(D)
        else:
            D = row
        nextname = nextrow["name"]
        D["name"] = name
        D["age"] = age
        D["phone"] = phone
        table_json["highlight"] = nextname
        # format as a json string
        jsontable = jsonParse.format(table_json)
        jsontablestr = jsonParse.format(jsontable)
        nextnamestr = jsonParse.format(nextname)
        # return js function call: automatically edit the next row...
        result = "%s ( %s, %s );" % (updateFnName, jsontablestr, nextnamestr)
        #pr "result::"
        #pr result
        start_response("200 OK", [('Content-Type', "application/javascript")])
        ##pr "result=", repr(result)
        return [stream.mystr(result)]

__middleware__ = table
    
